import { fileURLToPath, URL } from "node:url";

import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueDevTools from "vite-plugin-vue-devtools";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { loadEnv } from "vite";
import path from "path";

// https://vite.dev/config/
export default ({ mode }: any) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const { VITE_VERSION, VITE_PORT, VITE_BASE_URL, VITE_API_URL } = env;
  console.log(`🚀 API_URL = ${VITE_API_URL}`);
  console.log(`🚀 VERSION = ${VITE_VERSION}`);
  return {
    define: {
      __APP_VERSION__: JSON.stringify(VITE_VERSION)
    },
    base: VITE_BASE_URL,
    server: {
      port: parseInt(VITE_PORT),
      proxy: {
        "/api": {
          target: VITE_API_URL,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, "")
        }
      },
      host: true
    },
    // 路径别名
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "@views": resolvePath("src/views"),
        "@comps": resolvePath("src/components"),
        "@imgs": resolvePath("src/assets/img"),
        "@icons": resolvePath("src/assets/icons"),
        "@utils": resolvePath("src/utils"),
        "@stores": resolvePath("src/store"),
        "@plugins": resolvePath("src/plugins"),
        "@styles": resolvePath("src/assets/styles")
      }
    },
    build: {
      target: "es2015",
      outDir: "dist",
      chunkSizeWarningLimit: 2000,
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true, // 生产环境去除 console
          drop_debugger: true // 生产环境去除 debugger
        }
      },
      // rollupOptions:{
      //   output: {
      //     manualChunks: {
      //       vendor: ['vue', 'vue-router', 'pinia', 'element-plus']
      //     }
      //   }
      // },
      dynamicImportVarsOptions: {
        warnOnError: true,
        exclude: [],
        include: ["src/views/**/*.vue"]
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      // 自动导入 components 下面的组件，无需 import 引入
      Components({
        deep: true,
        extensions: ["vue"],
        dirs: ["src/components"], // 自动导入的组件目录
        resolvers: [ElementPlusResolver()],
        dts: "src/types/components.d.ts" // 指定类型声明文件的路径
      }),
      AutoImport({
        imports: ["vue", "vue-router", "pinia"],
        resolvers: [ElementPlusResolver()],
        dts: "src/types/auto-imports.d.ts",
        eslintrc: {
          // 这里先设置成true然后pnpm dev 运行之后会生成 .auto-import.json 文件之后，在改为false
          enabled: true,
          filepath: "./.auto-import.json",
          globalsPropValue: true
        }
      })
    ],
    css: {
      preprocessorOptions: {
        // sass variable and mixin
        scss: {
          api: "modern-compiler",
          additionalData: `
            @use "@styles/variables.scss" as *; @use "@styles/mixin.scss" as *;
          `
        }
      }
      // postcss: {
      //   plugins: [
      //     {
      //       postcssPlugin: 'internal:charset-removal',
      //       AtRule: {
      //         charset: (atRule) => {
      //           if (atRule.name === 'charset') {
      //             atRule.remove()
      //           }
      //         }
      //       }
      //     }
      //   ]
      // }
    }
  };
};

function resolvePath(paths: string) {
  return path.resolve(__dirname, paths);
}
